package com.buss.controller;

import com.baomidou.kisso.web.waf.request.WafRequestWrapper;
import com.buss.storage.StorageFileNotFoundException;
import com.buss.storage.StorageService;
import com.buss.util.Constant;
import com.buss.util.map.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/test")
public class FileUploadTestController extends BaseFileController {

    private final StorageService storageService;

    @Autowired
    public FileUploadTestController(StorageService storageService) {
        this.storageService = storageService;
    }

    @GetMapping("/")
    public String listUploadedFiles(Model model) throws IOException {
        System.out.println("## test/upload - page");

        model.addAttribute("files", storageService
                .loadAll()
                .map(path ->
                        MvcUriComponentsBuilder
                                .fromMethodName(FileUploadTestController.class, "serveFile", path.getFileName().toString())
                                .build().toString())
                .collect(Collectors.toList()));

        return "uploadFormTest";
    }

    @GetMapping("/files/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        System.out.println("## test/upload - 文件浏览");

        Resource file = storageService.loadAsResource(filename);
        return ResponseEntity
                .ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"")
                .body(file);
    }

    @PostMapping("/")
    @ResponseBody
    public Map<String, Object> handleFileUpload (
            @RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<String,Object>();
        /**
         * 过滤 XSS SQL 注入
         */
        WafRequestWrapper wr = new WafRequestWrapper(request);
        String moduleCode = wr.getParameter("moduleCode");  // 模块编码
        String typeCode = wr.getParameter("typeCode"); // 文件类型编码
        // 参数检验
		if (StringUtils.isBlank(moduleCode) || StringUtils.isBlank(typeCode)) {
            response.put(Constant.COMMON_RETURN_KEY, new Result().inputParamIsNullError());
			return response;
		}

        String filePath = upload(file , moduleCode);
        LOG.info("上传路径="+filePath);
        String fileWebUrl = "http://127.0.0.1:81/repo/" + moduleCode + "/"+file.getOriginalFilename();
        LOG.info("访问路径="+fileWebUrl);
        // 存数据库
        // TODO...

        Map<String, Object> data = new HashMap<String,Object>();
        data.put("PATH", fileWebUrl);
        response.put(Constant.COMMON_RETURN_KEY, new Result().success());
        response.put("data", data);
        return response;
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }

}
